<template>
  <div :class="styles['detail']" v-loading="pageLoading">
<!--    标题条-->
    <DrawerHeader :title="config.DrawerHeader_title" @close="goBack"/>
<!--    订单详情信息-->
    <DrawerInfo :ul-props="config.DrawerInfo_ulProps" :state="detailState" :isVip="isVip"/>
    <h4 v-if="config.H4_stepTip_open" :class="[styles['tips'], 'ato-mb-12']">温馨提示：开箱初审必须按照①②③④顺序完成以下步骤</h4>
<!--    视频、大合照、卡牌数量-->
    <DrawerUploadBar v-model="drawerUploadData" :orderNo="orderNo" :trackingNo="trackingNo" :disabled="disabled"/>
    <h4 class="ato-sub-title ato-mb-8 ato-mt-18"><i>④</i>同批次签收的送卡订单--单张卡牌初审（扫描高清图）：</h4>
<!--    卡牌订单tab切换-->
    <CardTypeTabs v-model="cardOrderTab.currentTab" :list="cardOrderTab.list" :check="!disabled" @change="cardTypeTabChange"/>
    <div class="ato-detail-title-bar ato-mt-18">
      <b class="ato-mr-6">1、入库订单类型：</b>
      <span>{{ matchResultMap[detailState.matchResult] || '-' }}</span>
    </div>
    <div class="ato-flex-center-both ato-padding-16">
      <b>2、单张卡牌初审：</b>
      <div class="ato-flex">
        <el-button v-if="config.ElButton_printCardTag_open" @click="printCardTagOpen = true" type="primary">打印本订单的卡牌标签</el-button>
        <el-button v-if="config.ElButton_batchPutStore_open" type="primary" class="ato-w160" @click="batchPutStore">批量确认入库</el-button>
        <el-button v-if="config.ElButton_batchReturnCard_open" class="ato-w160 ato-mr-12" @click="batchReturnCard">批量回寄卡牌</el-button>
        <el-checkbox v-if="config.ElCheckbox_checkAll_open" v-model="allCheck.checked" :indeterminate="allCheck.isIndeterminate" @change="handleCheckedAll" label="全选"/>
      </div>
    </div>
<!--    卡牌列表-->
    <CardList
        ref="cardListRef"
        :isVip="isVip"
        :prop="config.CardList_prop"
        :disabled="disabled"
        :orderNo="cardOrderTab.orderNo"
        @firstReview="firstReview"
        @updateImage="updateImage"
        @resetFirstReview="resetFirstReview"
        @handleChecked="handleChecked"
        @handleCardStatus="handleCardStatus"
    />
    <div class="ato-flex-center ato-mt-24 ato-mb-24">
      <el-button v-if="config.ElButton_prevOrder_open" :disabled="cardOrderTab.isStartTab" type="primary" @click="onPrevOrder" class="ato-w160 ato-ml-12 ato-mr-12" size="large">上一个订单</el-button>
      <el-button v-if="config.ElButton_nextOrder_open" :disabled="cardOrderTab.isEndTab" type="primary" @click="onNextOrder" class="ato-w160" size="large">下一个订单</el-button>
      <el-button v-if="config.ElButton_submitReview_open" :disabled="!cardOrderTab.isAllChecked" type="primary" @click="submitReview" class="ato-w160" size="large">提交复核</el-button>
      <el-button v-if="config.ElButton_printCardOrder_open" type="primary" @click="onPrintCardOrders" class="ato-mr-24" size="large">打印全部送卡订单（{{ cardOrderTab.list.length }}单）</el-button>
      <el-button v-if="config.ElButton_goBack_open" @click="goBack" class="ato-w160" size="large">返回</el-button>
      <el-button v-if="config.ElButton_printPutStoreOrder_open" type="primary" size="large" @click="onPrintCardOrders">打印全部入库单（{{ cardOrderTab.list.length }}单）</el-button>
    </div>
<!--    填写卡牌回寄信息弹窗-->
    <WriteCardLogisticsDialog v-if="config.WriteCardLogisticsDialog_open" v-model="cardLogisticsWrite.open" :state="cardLogisticsWrite.state" @submit="updateCardList"/>
<!--    回显卡牌回寄信息-->
    <ReturnCardLogisticsDialog v-if="config.ReturnCardLogisticsDialog_open" v-model="cardLogisticsReturned.open" :cardId="cardLogisticsReturned.cardId"/>
<!--    打印送卡订单-->
    <PrintCardOrders
        v-if="config.PrintCardOrders_open"
        v-bind="config.PrintCardOrders_bindProps"
        :open="printCardOrdersOpen"
        :isVip="isVip"
        :stateList="cardOrderTab.list"
        @close="printCardOrdersOpen = false"
    />
    <PrintCardTag
        :open="printCardTagOpen"
        :stateList="cardOrderTab.list"
        @close="printCardTagOpen = false"
    />
  </div>
</template>

<script setup name="EnterStoreDetail">
import {reactive, ref, watch, onUnmounted, computed} from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { DrawerHeader, DrawerInfo, CardList, PrintCardOrders, PrintCardTag } from '@/components'
import WriteCardLogisticsDialog from './WriteCardLogisticsDialog'
import ReturnCardLogisticsDialog from './ReturnCardLogisticsDialog'
import CardTypeTabs from './CardTypeTabs'
import DrawerUploadBar from './DrawerUploadBar'
import {getInOrderDetailApi, putReviewApi} from '@/service/enterStore'
import {cardFirstReviewApi, cardStockApi, queryIsAllAuditApi, setCardInfoApi} from '@/service/card'
import formatterFile, {setUidByPictureList, defaultPictureList, fileToUpload} from '@/utils/formatterFile'
import {matchResultMap} from '@/common/statusMap'
import {configMap, cardTrialValidate} from './mixins'
import {updatePictureApi} from '@/service/picture'

const emit = defineEmits(['close', 'update'])
const props = defineProps({
  prop: {
    type: String,
    required: true
  },
  trackingNo: {
    type: String,
    required: true
  },
  orderNo: {
    type: String,
    required: true
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const config = computed(() => configMap.get(props.prop))
// 详情页loading
const pageLoading = ref(false)
// 详情页数据
const detailState = ref({})
// 是不是vip订单
const isVip = computed(() => {
  return detailState.value.matchResult === 2
})
// 上传视频图片及卡牌数量数据
const drawerUploadData = ref({
  videoFile: {
    id: 2,
    url: 'https://developcang.pokecolor.cn/media/warehouse/2024/09/3ef71672c8b21ac8cc50fbdef4762bfd.mp4'
  },
  pictureList: defaultPictureList,
  sendCount: '',
  actualCount: ''
})
// 卡牌初审tabs
const cardOrderTab = reactive({
  orderNo: '',
  currentTab: 0,
  list: [],
  isAllChecked: computed(() => cardOrderTab.list.filter(item => item.reviewed).length === cardOrderTab.list.length), // 已审核订单数量是否等于tab列表数量
  isEndTab: computed(() => cardOrderTab.currentTab === cardOrderTab.list.length - 1), // 当前tab是否为最后一个
  isStartTab: computed(() => cardOrderTab.currentTab === 0) // 当前tab是否为第一个
})

// 卡牌列表组件
const cardListRef = ref(null)
// 全选按钮操作
const allCheck = reactive({
  checked: false, // 全选
  isIndeterminate: false, // 半选
  checkedRows: [] // 已选行数据
})

// 填写回寄卡牌物流信息
const cardLogisticsWrite = reactive({
  open: false,
  state: {}
})

// 已回寄卡牌物流信息回显
const cardLogisticsReturned = reactive({
  open: false,
  cardId: ''
})

// 打印订单信息弹窗状态
const printCardOrdersOpen = ref(false)
// 打印卡牌标签弹窗状态
const printCardTagOpen = ref(false)

// 卡牌初审tab切换
function cardTypeTabChange (card) {
  cardOrderTab.orderNo = card.orderNo
}
// 下一个订单按钮
function onNextOrder () {
  cardOrderTab.currentTab ++
  cardTypeTabChange(cardOrderTab.list[cardOrderTab.currentTab])
}
// 上一个订单按钮
function onPrevOrder () {
  cardOrderTab.currentTab --
  cardTypeTabChange(cardOrderTab.list[cardOrderTab.currentTab])
}
// 返回
function goBack () {
  emit('close')
}

// 获取详情数据
async function getDetailState () {
  pageLoading.value = true
  const res = await getInOrderDetailApi({
    trackingNo: props.trackingNo
  })
  if(res.code === __code) {
    detailState.value = res.data
    // 同批次签收的送卡订单列表
    cardOrderTab.list = res.data?.orderInfos || []
    cardOrderTab.currentTab = res.data?.orderInfos?.findIndex(item => item.orderNo === props.orderNo) || 0
    // 开箱视频&&大合照
    const { pictureList, videoFile } = formatterFile(res.data?.imageInfos || [])
    const targetPictureList = setUidByPictureList(pictureList || defaultPictureList, res.data?.orderSetId || '')
    drawerUploadData.value = {
      videoFile: videoFile || {id: '', url: ''},
      pictureList: props.disabled ? targetPictureList.filter(pic => pic.url) : targetPictureList,
      sendCount: res.data?.sendCount || 0,
      actualCount: res.data?.actualCount || 0
    }
  }
  pageLoading.value = false
}

// 检查当前订单号已全部完成初审,更新卡牌初审当前tab的checked状态
async function queryIsAllAuditByOrder () {
  const res = await queryIsAllAuditApi(props.orderNo)
  if (res.code === __code) {
    // 更新卡牌初审当前tab的checked状态
    const reviewed = res.data?.reviewed || false
    cardOrderTab.list[cardOrderTab.currentTab].reviewed = reviewed
    if (reviewed) ElMessage.success('当前订单号已全部完成初审,可切换下一个订单')
  }
}

// 更新卡牌正面、背面、贴标图片
async function updateImage (row, prop) {
  await updatePictureApi(fileToUpload({[prop]: row[prop]})) // 更新图片
}

// 初审（通过/不通过）
async function firstReview (row) {
  // 当选择初审通过时，初始化不通过原因
  if (row.firstReview === 1) row.firstReason = ''
  // 校验
  if (cardTrialValidate(row)) {
    // 校验通过 发送卡牌修改请求
    const {cardId, rating, ratingNo, score, firstReason, firstReview  } = row
    const results = await Promise.all([
      setCardInfoApi({cardId, rating, ratingNo, score}), // 更新评级类型、分数、评级号码
      cardFirstReviewApi({cardId, firstReason, firstReview}) // 修改初审状态
    ])
    // 全部接口成功
    if (results.every(res => res.code === __code)) {
      ElMessage.success('初审操作成功')
      // 不用刷新表格，成功后修改初审状态为待复审
      row.auditStatus = 1
      // 检查当前订单号已全部完成初审,更新卡牌初审当前tab的checked状态
      await queryIsAllAuditByOrder()
    }
  } else {
    // 校验不通过 初始化数据
    row.firstReason = ''
    row.firstReview = 0
  }
}
// 重新审核
function resetFirstReview (row) {
  ElMessageBox.confirm('重新审核，将清除该卡牌的初审信息', '提示', {
    confirmButtonText: '重新审核',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  }).then(async () => {
    // 修改初审状态-初始化
    const res = await cardFirstReviewApi({
      cardId: row.cardId,
      firstReason: '',
      firstReview: 0
    })
    if (res.code === __code) {
      ElMessage.success('重新审核操作成功')
      // 不用刷新表格，重新审核后初始化初审信息
      row.firstReason = ''
      row.firstReview = 0
      row.auditStatus = 0
      // 检查当前订单号已全部完成初审,更新卡牌初审当前tab的checked状态
      await queryIsAllAuditByOrder()
    }
  })
}
// 提交复核
async function submitReview () {
  const res = await putReviewApi(props.trackingNo)
  if (res.code === __code) {
    ElMessage.success('提交复核成功')
    // 表格数据更新
    emit('update')
    // 调起送卡订单订单查看
    onPrintCardOrders()
  }
}

// 批量入库确认
function batchPutStore () {
  // 没选择时
  if (allCheck.checkedRows.length === 0) return ElMessage.warning('请勾选需要处理的卡牌！')
  // 当是vip订单，选择中的卡牌必须全是有上传卡牌贴标stickerPhoto
  if (isVip.value && allCheck.checkedRows.some(row => !row.stickerPhoto?.url)) return ElMessage.warning('所选卡牌中存在未上传卡牌贴标，请拍照后重新选择！')
  // 选择中有待勾选回寄卡牌
  if (allCheck.checkedRows.some(row => row.cardStatus === 3)) return ElMessage.warning('所选卡牌中存在待回寄，无法操作批量确认入库，请重新选择！')
  const cardIds = allCheck.checkedRows.map(row => row.cardId)
  handlePutStore(cardIds)
}
// 批量回寄卡牌确认
function batchReturnCard () {
  // 没选择时
  if (allCheck.checkedRows.length === 0) return ElMessage.warning('请勾选需要处理的卡牌！')
  // 当是vip订单，选择中的卡牌必须全是有上传卡牌贴标stickerPhoto
  if (isVip.value && allCheck.checkedRows.some(row => !row.stickerPhoto?.url)) return ElMessage.warning('所选卡牌中存在未上传卡牌贴标，请拍照后重新选择！')
  // 勾选中有待入库卡牌
  if (allCheck.checkedRows.some(row => row.cardStatus === 1)) return ElMessage.warning('所选卡牌中存在待入库，无法操作批量回寄卡牌，请重新选择！')
  const cardIds = allCheck.checkedRows.map(row => row.cardId)
  handleReturnCard(cardIds)
}
// 全选
function handleCheckedAll (val) {
  cardListRef.value.handleCheckedAll(val) // 调用卡牌列表全选/全不选
}
// 单选回调
function handleChecked ({allChecked, isIndeterminate, checkedRows}) {
  allCheck.checked = allChecked
  allCheck.isIndeterminate = isIndeterminate
  allCheck.checkedRows = checkedRows
}
// 入库状态回调
function handleCardStatus (row) {
  handleReturnedCard(row.cardId)
  switch (row.cardStatus) {
  // case 1:
  //   handlePutStore([row])
  //   break
  case 3:
    handleReturnCard([row.cardId])
    break
  case 4:
    handleReturnedCard(row.cardId)
    break
  default:
    break
  }
}
// 待入库处理
async function handlePutStore (cardIds) {
  const res = await cardStockApi({cardIds, orderNo: cardOrderTab.orderNo})
  if (res.code === __code) {
    ElMessage.success('入库成功！')
    updateCardList()
  }
}
// 回寄卡牌弹窗
function handleReturnCard (cardIds) {
  const {sendPerson, sendPhone, sendAddress} = detailState.value
  cardLogisticsWrite.open = true
  cardLogisticsWrite.state = {
    cardIds,
    sendPerson,
    sendAddress,
    sendPhone,
    orderNo: cardOrderTab.orderNo
  }
}
// 已回寄卡牌弹窗
function handleReturnedCard (cardId) {
  cardLogisticsReturned.open = true
  cardLogisticsReturned.cardId = cardId
}
// 更新卡牌列表
function updateCardList () {
  cardListRef.value.onLoad()
  // 初始化数据
  allCheck.checked = false
  allCheck.isIndeterminate = false
  allCheck.checkedRows = []
}

// 打开打印订单弹窗
function onPrintCardOrders () {
  printCardOrdersOpen.value = true
}


// 监听id变化更换数据
const unwatch = [
  watch(() => props.trackingNo, () => {
    if(props.trackingNo)  getDetailState()
  }, {immediate: true}),
  watch(() => props.orderNo, () => {
    if(props.orderNo) cardOrderTab.orderNo = props.orderNo
  }, {immediate: true})
]

onUnmounted(() => {
  // 取消监听
  unwatch.forEach(wa => wa())
})
</script>

<style lang="less" module="styles" src="./index.less"></style>
